package org.bonorsoft.modules.dingding.controller;

import java.util.Arrays;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.bonorsoft.common.api.vo.Result;
import org.bonorsoft.common.aspect.annotation.PermissionData;
import org.bonorsoft.common.constant.UserConstants;
import org.bonorsoft.common.exception.WilliamBootException;
import org.bonorsoft.common.system.query.QueryGenerator;
import org.bonorsoft.common.util.DateUtils;
import org.bonorsoft.modules.dingding.entity.SysDingUser;
import org.bonorsoft.modules.dingding.entity.SysRole;
import org.bonorsoft.modules.dingding.service.ISysDingUserService;
import org.bonorsoft.modules.dingding.service.ISysRoleService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import org.bonorsoft.common.aspect.annotation.AutoLog;
import org.bonorsoft.common.system.base.controller.BonorController;

import org.bonorsoft.modules.sysutils.redisutil.RedisOperate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

/**
 * @Description: 角色
 * @Author: WilliamYe
 * @Date:   2020-11-13
 * @Version: V1.0
 */
@Slf4j
@Controller
@RequestMapping("/system/role")
public class SysRoleController extends BonorController<SysRole, ISysRoleService> {
	private String prefix = "system/role";

	@Autowired
	private ISysRoleService sysRoleService;

	@Autowired
	private ISysDingUserService userService;

	/**
	 *首页
	 */
	@RequiresPermissions("system:role:view")
	@GetMapping()
	public String index()
	{
		return prefix + "/role";
	}

	/**
	 * 分页列表查询
	 *
	 * @param sysRole
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	@AutoLog(value = "角色-分页列表查询")
	@RequiresPermissions("system:role:list")
	@GetMapping(value = "/list")
	@ResponseBody
	public Result<?> queryPageList(SysRole sysRole,
								   @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
								   @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
								   HttpServletRequest req) {
		QueryWrapper<SysRole> queryWrapper = QueryGenerator.initQueryWrapper(sysRole, req.getParameterMap());
		Page<SysRole> page = new Page<SysRole>(pageNo, pageSize);
		queryWrapper.ne("group_id", -1)
				.eq("del_flag", 0);
		IPage<SysRole> pageList = sysRoleService.page(page, queryWrapper);
		return Result.ok(pageList);
	}

	/**
	 * 添加
	 *
	 * @param sysRole
	 * @return
	 */
	@AutoLog(value = "角色-添加")
	@PostMapping(value = "/add")
	public Result<?> add(@RequestBody SysRole sysRole) {
		sysRoleService.save(sysRole);
		return Result.ok("添加成功！");
	}

	/**
	 * 编辑页面
	 */
	@GetMapping("/edit/{id}")
	public String edit(@PathVariable("id") String id, ModelMap map)
	{
		map.put("role", sysRoleService.getById(id));
		return prefix + "/edit";
	}

	/**
	 * 编辑
	 *
	 * @param sysRole
	 * @return
	 */
	@AutoLog(value = "角色-编辑")
	@RequiresPermissions("system:role:edit")
	@PostMapping(value = "/edit")
	@ResponseBody
	public Result<?> edit(@Validated SysRole sysRole, HttpServletRequest req) {
		//sysRoleService.checkRoleAllowed(sysRole);
		if (UserConstants.ROLE_NAME_KEY_NOT_UNIQUE.equals(sysRoleService.checkRoleUnique("name", sysRole, sysRole.getName())))
		{
			return Result.error("修改角色'" + sysRole.getName() + "'失败，角色名称已存在");
		}
		else if (UserConstants.ROLE_NAME_KEY_NOT_UNIQUE.equals(sysRoleService.checkRoleUnique("role_key", sysRole, sysRole.getRoleKey())))
		{
			return Result.error("修改角色'" + sysRole.getName() + "'失败，角色权限已存在");
		}
		sysRole.setUpdateBy(getLoginUserName());
		sysRole.setUpdateTime(DateUtils.getDate());
		//删除该角色下的所有用户的权限缓存
		RedisOperate.delUserShiroByRoleId(sysRole.getId());
		sysRoleService.updateRole(sysRole, req);
		return Result.ok("编辑成功!");
	}

	/**
	 * 通过id删除
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "角色-通过id删除")
	@DeleteMapping(value = "/delete")
	public Result<?> delete(@RequestParam(name="id",required=true) String id) {
		sysRoleService.removeById(id);
		return Result.ok("删除成功!");
	}

	/**
	 * 批量删除
	 *
	 * @param ids
	 * @return
	 */
	@AutoLog(value = "角色-批量删除")
	@RequiresPermissions("system:role:deleteBatch")
	@DeleteMapping(value = "/deleteBatch")
	@ResponseBody
	public Result<?> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
		try
		{
			this.sysRoleService.removeByIds(Arrays.asList(ids.split(",")));
			return Result.ok("批量删除成功！");
		}
		catch (Exception e)
		{
			return Result.error(e.getMessage());
		}

	}

	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "角色-通过id查询")
	@GetMapping(value = "/queryById")
	public Result<?> queryById(@RequestParam(name="id",required=true) String id) {
		SysRole sysRole = sysRoleService.getById(id);
		return Result.ok(sysRole);
	}

  /**
   * 导出excel
   *
   * @param request
   * @param sysRole
   */
  @RequestMapping(value = "/exportXls")
  public ModelAndView exportXls(HttpServletRequest request, SysRole sysRole) {
      return super.exportXls(request, sysRole, SysRole.class, "角色");
  }

  /**
   * 通过excel导入数据
   *
   * @param request
   * @param response
   * @return
   */
  @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
  public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
      return super.importExcel(request, response, SysRole.class);
  }

	/**
	 * 角色状态修改
	 */
	@AutoLog(value = "角色管理-角色状态修改", operateType = 3)
	@RequiresPermissions("system:role:edit")
	@PostMapping("/changeStatus")
	@ResponseBody
	public Result<?> changeStatus(SysRole role)
	{
		try {
			sysRoleService.checkRoleAllowed(role);
		}catch (Exception e){
			return Result.error(e.getMessage());
		}
		sysRoleService.updateById(role);
		return Result.ok("修改成功！");
	}

	/**
	 * 校验角色名称
	 */
	@PostMapping("/checkRoleNameUnique")
	@ResponseBody
	public String checkRoleNameUnique(SysRole role)
	{
		return sysRoleService.checkRoleUnique("name", role, role.getName());
	}

	/**
	 * 校验角色权限
	 */
	@PostMapping("/checkRoleKeyUnique")
	@ResponseBody
	public String checkRoleKeyUnique(SysRole role)
	{
		return sysRoleService.checkRoleUnique("role_key", role, role.getRoleKey());
	}

	/**
	 * 查看用户
	 */
	@RequiresPermissions("system:role:edit")
	@GetMapping("/authUser/{roleId}")
	public String authUser(@PathVariable("roleId") Integer roleId, ModelMap mmap)
	{
		mmap.put("role", sysRoleService.selectRoleById(roleId));
		return prefix + "/authUser";
	}

	/**
	 * 查询已分配用户角色列表
	 */
	@RequiresPermissions("system:role:list")
	@RequestMapping(value = "/authUser/allocatedList",method = RequestMethod.GET)
	@ResponseBody
	@PermissionData(value = "more", deptAlias = "d", userAlias = "u")
	public Result<?> allocatedList(SysDingUser sysDingUser,
								   @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
								   @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
								   HttpServletRequest req)
	{
		Page<SysDingUser> page = new Page<>(pageNo, pageSize);
		IPage<SysDingUser> pageList = userService.pageByConditions(page, sysDingUser, req);
		return Result.ok(pageList);
	}

	/**
	 * 角色分配数据权限
	 */
	@GetMapping("/authDataScope/{roleId}")
	public String authDataScope(@PathVariable("roleId") Integer roleId, ModelMap mmap)
	{
		mmap.put("role", sysRoleService.selectRoleById(roleId));
		return prefix + "/dataScope";
	}

	/**
	 * 保存角色分配数据权限
	 */
	@RequiresPermissions("system:role:edit")
	@AutoLog(value = "角色管理-分配数据权限", operateType = 2)
	@PostMapping("/authDataScope")
	@ResponseBody
	public Result<?> authDataScopeSave(SysRole role, HttpServletRequest req)
	{
		sysRoleService.checkRoleAllowed(role);
		role.setUpdateBy(getLoginUserName());
		if (sysRoleService.authDataScope(role, req) > 0)
		{
			return Result.ok("分配成功");
		}
		return Result.error("分配失败");
	}

}
